<template>
    <div class="app-container">
        <ViewLayoutSearchArea>
            <el-form ref="searchFormRef" :inline="true" :model="searchData">
                <el-form-item prop="name" label="网站名称">
                    <el-input v-model="searchData.name" placeholder="请输入关键词" />
                </el-form-item>
                <el-form-item prop="type" label="网站类型">
                    <el-select v-model="searchData.type" filterable placeholder="请选择网站类型">
                        <el-option v-for="item in TagOptionData" :key="item.id" :label="item.type" :value="item.type" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
                    <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </ViewLayoutSearchArea>
        <el-card v-loading="loading" shadow="never">
            <ViewLayoutToolbarArea>
                <div></div>
                <div>
                    <el-button type="primary" @click="handleAdd()">新建</el-button>
                </div>
            </ViewLayoutToolbarArea>
            <ViewLayoutTableArea>
                <el-table :data="tableData">
                    <el-table-column prop="name" label="网站名称" align="center" />
                    <el-table-column prop="type" label="网站类型" align="center" />
                    <el-table-column prop="keyWord" label="模糊搜索配置" align="center" />
                    <el-table-column prop="weight" label="排序" align="center" />
                    <el-table-column fixed="right" label="操作" width="150" align="center">
                        <template #default="scope">
                            <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)"
                                >编辑</el-button
                            >
                            <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)"
                                >删除</el-button
                            >
                        </template>
                    </el-table-column>
                </el-table>
            </ViewLayoutTableArea>
            <ViewLayoutPagerArea>
                <el-pagination
                    background
                    :layout="paginationData.layout"
                    :page-sizes="paginationData.pageSizes"
                    :total="paginationData.total"
                    :page-size="paginationData.pageSize"
                    :current-page="paginationData.currentPage"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </ViewLayoutPagerArea>
        </el-card>
        <!-- 新增/编辑 -->
        <el-dialog
            v-model="dialogVisible"
            :title="currentUpdateId === undefined ? '新建推荐网站 ' : '编辑推荐网站'"
            width="600"
            @close="resetForm"
        >
            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="130px" label-position="right">
                <el-form-item prop="name" label="网站名称">
                    <el-input v-model="formData.name" placeholder="请输入网站名称" />
                </el-form-item>
                <el-form-item prop="action" label="打开方式">
                    <el-select v-model="formData.action" placeholder="请选择打开方式">
                        <el-option
                            v-for="item in actionOptionData"
                            :key="item.type"
                            :label="item.name"
                            :value="item.type"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item prop="type" label="网站类型">
                    <el-select v-model="formData.type" filterable placeholder="请选择网站类型">
                        <el-option v-for="item in TagAllOptionData" :key="item" :label="item" :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item prop="content" label="跳转URL">
                    <el-input v-model="formData.content" placeholder="请输入跳转URL" />
                </el-form-item>
                <el-form-item prop="weight" label="排序">
                    <el-input-number
                        v-model="formData.weight"
                        controls-position="right"
                        value-on-clear="null"
                        placeholder="请输入排序"
                    />
                </el-form-item>
                <el-form-item prop="scriptDelayRunTime" label="脚本延迟执行时间">
                    <el-input-number
                        v-model="formData.scriptDelayRunTime"
                        controls-position="right"
                        value-on-clear="null"
                        min="0"
                        placeholder="请输入时间"
                    />
                    <span class="script-delay-run-time">秒</span>
                </el-form-item>
                <el-form-item prop="scriptContent" label="网页内嵌脚本内容">
                    <el-input v-model="formData.scriptContent" placeholder="请输入网页内嵌脚本内容" />
                </el-form-item>
                <el-form-item prop="keyWord" label="模糊搜索配置">
                    <el-input v-model="formData.keyWord" placeholder="可配置多个用”,”隔开" />
                    <span class="notes">
                        注：基于网站名称默认会生成中文、拼音（大小写）、拼音首字母，仅配置仍需要扩充的即可如：英文、别称等
                    </span>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleCreate">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import {reactive, ref, watch, onMounted} from 'vue';
import {addTableDataApi, deleteTableDataApi, updateTableDataApi, getTableDataApi} from '@/api/recommended-web/index';
import {getTagOptionApi, getAllTagOptionApi} from '@/api/common/index';
import type {GetTableData} from '@/api/recommended-web/types/recommended-web';
import type {GetTagData, GetAllTagData} from '@/api/common/types/common';
import type {FormInstance, FormRules, UploadProps} from 'element-plus';
import {ElMessage, ElMessageBox} from 'element-plus';
import {Search, Refresh} from '@element-plus/icons-vue';
import {getUniqueArrayObjects} from '@/constants/tool';
import {usePagination} from '@/hooks/usePagination';
import {actionOptionData} from '@/constants/common';
import {
    ViewLayoutSearchArea,
    ViewLayoutToolbarArea,
    ViewLayoutTableArea,
    ViewLayoutPagerArea
} from '@/layout/components';

defineOptions({
    name: 'RecommendedWeb'
});

const searchData = reactive({
    name: null, // 网站名称
    type: '' // 网站类型
});
const formData = reactive<any>({
    name: '', // 网站名称
    action: '', // 打开方式
    type: '', // 网站类型
    content: '', // 网站URL
    weight: null, // 排序
    keyWord: '', // 模糊搜索
    scriptContent: '', // 网页内嵌脚本内容
    scriptDelayRunTime: null // 注入脚本延迟运行时间
});
const loading = ref<boolean>(false);
const dialogVisible = ref<boolean>(false);
const searchFormRef = ref<InstanceType<typeof FormInstance>>();
const formRef = ref<InstanceType<typeof FormInstance>>();
const currentUpdateId = ref<undefined | number>(undefined);
const TagOptionData = ref<GetTagData[]>([]);
const TagAllOptionData = ref<GetAllTagData[]>([]);
const tableData = ref<GetTableData[]>([]);
const {paginationData, handleCurrentChange, handleSizeChange} = usePagination();

// 表单 rules 规则
const formRules = reactive<InstanceType<typeof FormRules>>({
    name: [{required: true, trigger: 'blur', message: '请输入网站名称'}],
    action: [{required: true, trigger: 'change', message: '请选择打开方式'}],
    type: [{required: true, trigger: 'change', message: '请选择网站类型'}],
    content: [{required: true, trigger: 'blur', message: '请输入跳转URL'}],
    weight: [{required: true, trigger: 'blur', message: '请输入排序'}]
});

// 新建/编辑 确认按钮
const handleCreate = () => {
    formRef.value?.validate((valid: boolean, fields: any) => {
        if (valid) {
            if (currentUpdateId.value === undefined) {
                addTableDataApi(formData)
                    .then(({data: res}) => {
                        const {code, data} = res;
                        if (code === 100000) {
                            ElMessage.success('新增成功');
                            getTableData();
                        } else {
                            ElMessage.error(data);
                        }
                    })
                    .finally(() => {
                        dialogVisible.value = false;
                    });
            } else {
                updateTableDataApi({
                    id: currentUpdateId.value,
                    ...formData
                })
                    .then(({data: res}) => {
                        const {code, data} = res;
                        if (code === 100000) {
                            ElMessage.success('修改成功');
                            getTableData();
                        } else {
                            ElMessage.error(data);
                        }
                    })
                    .finally(() => {
                        dialogVisible.value = false;
                    });
            }
        } else {
            console.error('表单校验不通过', fields);
        }
    });
};

// 删除
const handleDelete = (row: GetTableData) => {
    ElMessageBox.confirm(`删除后不可恢复, 你还要继续吗?`, '确认删除该网站', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        deleteTableDataApi(row.id)
            .then(({data: res}) => {
                const {code, data} = res;
                if (code === 100000) {
                    ElMessage.success('删除成功');
                    getTableData();
                } else {
                    ElMessage.error(data);
                }
            })
            .catch(() => {
                ElMessage({
                    type: 'warning',
                    message: '删除失败, 请重试'
                });
            });
    });
};

// 新建推荐网站
const handleAdd = () => {
    resetForm();
    dialogVisible.value = true;
};

// 编辑推荐网站
const handleUpdate = (row: GetTableData) => {
    const {id, name, action, type, content, weight, keyWord, scriptContent, scriptDelayRunTime} = row;
    currentUpdateId.value = id;
    Object.assign(formData, {name, action, type, content, weight, keyWord, scriptContent, scriptDelayRunTime});
    dialogVisible.value = true;
};

// 查询类型选项
const getTagOption = () => {
    const newItem = {
        keyWord: ''
    };
    getTagOptionApi(newItem, 'website')
        .then(({data: res}) => {
            if (res.code === 100000) {
                TagOptionData.value = getUniqueArrayObjects(res.data, 'type');
            }
        })
        .catch(() => {
            TagOptionData.value = [];
        });
};

// 查询工具类型-全量类型
const getAllTagOption = () => {
    const newItem = {
        name: '',
        type: 'WEBSITE'
    };
    getAllTagOptionApi(newItem)
        .then(({data: res}) => {
            if (res.code === 100000) {
                TagAllOptionData.value = res.data;
            }
        })
        .catch(() => {
            TagAllOptionData.value = [];
        });
};

// 查询列表数据
const getTableData = () => {
    loading.value = true;
    const {name, type} = searchData;
    const newItem = {
        key: name,
        type,
        page: paginationData.currentPage,
        size: paginationData.pageSize
    };
    getTableDataApi(newItem)
        .then(({data: res}) => {
            if (res.code === 100000) {
                const {content, number, totalElements} = res.data;
                tableData.value = content;
                paginationData.currentPage = number; //  当前页码
                paginationData.total = totalElements; // 总数
            }
        })
        .catch(() => {
            tableData.value = [];
        })
        .finally(() => {
            loading.value = false;
        });
};

// 查询
const handleSearch = () => {
    paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1);
};

onMounted(() => {
    getTagOption();
    getAllTagOption();
});

// 监听分页参数的变化
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, {immediate: true});

// 重置查询表单
const resetSearch = () => {
    searchFormRef.value?.resetFields();
    handleSearch();
};

// 重置新建/编辑表单
const resetForm = () => {
    currentUpdateId.value = undefined;
    formRef.value?.resetFields();
    formData.name = '';
    formData.action = '';
    formData.type = '';
    formData.content = '';
    formData.weight = null;
    formData.keyWord = '';
};
</script>

<style lang="less" scoped>
.notes {
    color: #8d9998;
    line-height: 20px;
    margin-top: 15px;
}
</style>
